package cn.tedu.basic;
//测试单例设计模式
public class Test3_Singleton {
    public static void main(String[] args) {
        //实现单例
        System.out.println(Student.getStudent());
        System.out.println(RunTime.getRunTime());
        System.out.println(Doctor.get());
        System.out.println(Doctor.get());
        //equals ：如果使用object的就比较地址值，如果重写了就比较属性值
        //==: 比较基本类型的值，也可以比较引用类型的地址值
        Student s =Student.getStudent();
        Student s1 =Student.getStudent();
        System.out.println(s==s1);//相等
        Teacher t1 =Teacher.getTeacher();
        Teacher t2 =Teacher.getTeacher();
        System.out.println(t1==t2);
        KongJie kj =KongJie.getKongJie();
        KongJie kj1 =KongJie.getKongJie();
        System.out.println(kj == kj1);

    }
}
//饿汉式--写法简单，没有任何隐患，经常用
 class Student{
    //1.私有化构造方法，不让外界调用
    private Student(){ }
    //2.自己给外界创建一个
     private static Student s =new Student();
    //3.提供方法，并返回s共外界调用
     public static Student getStudent(){
         return s;
     }
}
class RunTime{
    private RunTime(){} //私有构造方法
    private static RunTime runTime =new RunTime();//自己创建一个
    public static RunTime getRunTime(){
        return runTime;//提供方法。给外界调用
    }
}
class Doctor{
    private Doctor(){}
    private static Doctor d =new Doctor();
    public static Doctor get(){
        return d;
    }
}
class Teacher{
    private Teacher(){}
    private static Teacher t =new Teacher();
    public static Teacher getTeacher(){
        return t;
    }
}
//懒汉式--面试常见--按需加载/延迟加载--

class KongJie{
    private KongJie(){}
    private static KongJie kj;
    synchronized public static KongJie getKongJie(){//上同步锁，直接锁方法
        if (kj==null){
            kj=new KongJie();//需要时才new
        }
        return  kj;
    }
}
class XueSheng{
    private XueSheng(){}
    private static XueSheng XS;
    synchronized public static XueSheng getXueSheng(){
        if (XS==null){
            XS=new XueSheng();
        }
        return XS;
    }
}
class Zhang{
    private Zhang(){}
    private static Zhang z =new Zhang();
    public static  Zhang getZhang(){
        return z ;
    }
}
class You{
    private You(){}
    private static You y ;
    synchronized public static You get(){
        if(y == null){
            y=new You();
        }
        return y;
    }
}